/*
 * GoodsDetailFragment.java
 * business
 *
 * Created by SunDing on 2016/9/9.
 *
 * Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.goodsdetail;

import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yidiandao.business.R;
import com.yidiandao.business.base.BaseEventFragment;
import com.yidiandao.business.constant.Intents;
import com.yidiandao.business.data.bean.Goods;
import com.yidiandao.business.data.bean.ShareEntity;
import com.yidiandao.business.data.bean.Shop;
import com.yidiandao.business.data.event.RefreshGoodsDetailEvent;
import com.yidiandao.business.data.response.GoodsDetailResponse;
import com.yidiandao.business.ui.widget.dialog.GoodsShoppingDialog;
import com.yidiandao.business.ui.adapter.GoodsDetailPagerAdapter;
import com.yidiandao.business.ui.goodsdetail.info.GoodsDetailInfoFragment;
import com.yidiandao.business.ui.goodsdetail.info.GoodsDetailInfoPresenter;
import com.yidiandao.business.ui.goodsdetail.standard.GoodsDetailStandardFragment;
import com.yidiandao.business.ui.goodsdetail.standard.GoodsDetailStandardPresenter;
import com.yidiandao.business.ui.goodsdetail.value.GoodsDetailValueFragment;
import com.yidiandao.business.ui.goodsdetail.value.GoodsDetailValuePresenter;
import com.yidiandao.business.ui.main.MainActivity;
import com.yidiandao.business.ui.main.home.HomeFragment;
import com.yidiandao.business.ui.main.shoppingcart.ShoppingCartFragment;
import com.yidiandao.business.ui.main.shoppingcart.confirmorder.ConfirmOrderActivity;
import com.yidiandao.business.ui.shopdetail.ShopDetailActivity;
import com.yidiandao.business.ui.widget.dialog.CallPhoneDialog;
import com.yidiandao.business.ui.widget.dialog.LoadingDialog;
import com.yidiandao.business.ui.widget.dialog.ShareDialog;
import com.yidiandao.business.ui.widget.view.BannerView;
import com.yidiandao.business.ui.widget.view.FavorableLayout;
import com.yidiandao.business.ui.widget.view.TimerLayout;
import com.yidiandao.business.utils.ImageLoader;
import com.yidiandao.business.utils.PriceUtils;
import com.yidiandao.business.utils.TextRenderUtils;
import com.yidiandao.business.utils.UIUtils;
import com.yidiandao.business.utils.UmengUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

/**
 * 商品详情页View层.
 */
public class GoodsDetailFragment extends BaseEventFragment
        implements GoodsDetailContract.View, OnClickListener {

    private static final String TAG = GoodsDetailFragment.class.getSimpleName();
    int alpha = 0; //上一次的alpha值
    boolean mHasCollect;
    private GoodsDetailContract.Presenter mPresenter;
    private LoadingDialog mLoadingDialog;
    private AppBarLayout mAppbarLayout;
    private BannerView mBannerView;
    private TextView mTvGoodsName;
    private TextView mTvGoodsPrice;
    private Toolbar mToolbar;
    private TextView mTvTitle;
    private LinearLayout mLlGoodsShop;
    private ImageView mIvShopInfoImage;
    private TextView mTvShopName;
    private TextView mTvShopDetail;
    private TextView mTvShopEnter;
    private TextView mTvStockNumber;
    private RelativeLayout mRlCart;
    private TextView mTvToBuy;
    private RelativeLayout mRlCollect;
    private ImageView mIvCollect;
    private LinearLayout mLlGoodsPrice;
    private RelativeLayout mRlGoodsBottom;
    private ImageButton mIbtnBack;
    private TextView mTvCartNum;
    private ImageButton mIbtnShare;
    private RelativeLayout mRlytGoToShoppingCart;
    private ViewPager mViewPager;
    private TabLayout mTabLayout;
    private LinearLayout mLlGoodsPromotion;
    private FavorableLayout mFavorableLayout;
    private TextView tvPriceOntrast;
    private TextView tvLogisticsInfo;
    private TextView tvLogisticsPrice;
    private TextView mTvMarketPrice;
    private TextView mTvProfit;
    private TextView mTvTip;
    private TextView mTvSold;
    private TextView mTvCart;
    private RelativeLayout mRlHome;
    private LinearLayout mLlSigleUnit;
    private LinearLayout mLlLogistics;
    private View mViewPlaceHolder;
    private LinearLayout mLlActiveHeader;
    private TextView mTvPriceActive;
    private TextView mTvActiveStyle;
    private TextView mTvPricePast;
    private TextView mTvTipActive;
    private TimerLayout mTimerLayout;
    private LinearLayout mLlPrice;
    private TextView mTvLessNumber;
    private TextView mTvBgCircle;
    private GoodsDetailPagerAdapter mPagerAdapter;
    private int goodsStockNumber;
    private boolean mCanCart;
    private boolean mCanBuy;
    /**
     * 活动是否正在进行中
     */
    private boolean mIsRunning;

    private GoodsDetailResponse.DataBean mDataBean;
    private Shop mShop;
    private GoodsShoppingDialog mGoodsDetailBuyManager;
    private int scrollHeight;
    private String goodsId;
    private GoodsDetailInfoFragment mGoodsDetailInfoFragment;
    private GoodsDetailStandardFragment mGoodsDetailStandardFragment;
    private GoodsDetailValueFragment mGoodsDetailValueFragment;
    private LinearLayout mLlServicePhone;
    private TextView mTvPhone;
    private String mPhone;
    private TextView mTvSaleOff;
    private TextView mTvMinNum;

    public static GoodsDetailFragment getInstance(Bundle bundle) {
        GoodsDetailFragment fragment = new GoodsDetailFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (null != savedInstanceState) {
            mPagerAdapter = new GoodsDetailPagerAdapter(getChildFragmentManager());
            //noinspection RestrictedApi
            List<Fragment> fragments = getChildFragmentManager().getFragments();
            for (Fragment fragment : fragments) {
                if (fragment instanceof GoodsDetailInfoFragment) {
                    mGoodsDetailInfoFragment = (GoodsDetailInfoFragment) fragment;
                } else if (fragment instanceof GoodsDetailStandardFragment) {
                    mGoodsDetailStandardFragment = (GoodsDetailStandardFragment) fragment;
                } else if (fragment instanceof GoodsDetailValueFragment) {
                    mGoodsDetailValueFragment = (GoodsDetailValueFragment) fragment;
                }
            }
            addFragment();
        }
    }

    @Override
    public void setPresenter(GoodsDetailContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    protected void initViews() {
        mLoadingDialog = new LoadingDialog(mActivity);
        mLoadingDialog.setCanceledOnTouchOutside(false);
        mGoodsDetailBuyManager = new GoodsShoppingDialog(mActivity);

        mLlLogistics = (LinearLayout) mRootView.findViewById(R.id.ll_logistics);
        mLlPrice = (LinearLayout) mRootView.findViewById(R.id.ll_price);
        mLlGoodsPrice = (LinearLayout) mRootView.findViewById(R.id.ll_goods_price);
        mAppbarLayout = (AppBarLayout) mRootView.findViewById(R.id.appbar_layout);
        mBannerView = (BannerView) mRootView.findViewById(R.id.goods_banner_view);
        mTvGoodsName = (TextView) mRootView.findViewById(R.id.tv_goods_name);
        mTvGoodsPrice = (TextView) mRootView.findViewById(R.id.tv_goods_price);
        mTvStockNumber = (TextView) mRootView.findViewById(R.id.tv_goods_stock);
        mToolbar = (Toolbar) mRootView.findViewById(R.id.toolbar);
        mTvTitle = (TextView) mRootView.findViewById(R.id.tv_title);
        mLlGoodsShop = (LinearLayout) mRootView.findViewById(R.id.ll_goods_shop);
        mIvShopInfoImage = (ImageView) mRootView.findViewById(R.id.iv_shop_info_image);
        mTvShopName = (TextView) mRootView.findViewById(R.id.tv_shop_name);
        mTvShopDetail = (TextView) mRootView.findViewById(R.id.tv_shop_detail);
        mTvShopEnter = (TextView) mRootView.findViewById(R.id.tv_shop_enter);
        mRlCart = (RelativeLayout) mRootView.findViewById(R.id.rl_cart);
        mTvToBuy = (TextView) mRootView.findViewById(R.id.tv_to_buy);
        mTvCart = (TextView) mRootView.findViewById(R.id.tv_to_cart);
        mRlCollect = (RelativeLayout) mRootView.findViewById(R.id.rl_collect);
        mRlHome = (RelativeLayout) mRootView.findViewById(R.id.rl_home);
        mIvCollect = (ImageView) mRootView.findViewById(R.id.iv_collect);
        mRlGoodsBottom = (RelativeLayout) mRootView.findViewById(R.id.rl_goods_bottom);
        mIbtnBack = (ImageButton) mRootView.findViewById(R.id.ibtn_back);
        mRlytGoToShoppingCart =
                (RelativeLayout) mRootView.findViewById(R.id.rlty_go_to_shopping_cart);
        mLlSigleUnit = (LinearLayout) mRootView.findViewById(R.id.ll_sigleUnit);
        mTvMarketPrice = (TextView) mRootView.findViewById(R.id.tv_market_price);
        mTvProfit = (TextView) mRootView.findViewById(R.id.tv_profit);
        mTvTip = (TextView) mRootView.findViewById(R.id.tv_tip);
        mTvSold = (TextView) mRootView.findViewById(R.id.tv_sold);
        mIbtnShare = (ImageButton) mRootView.findViewById(R.id.ibtn_share);
        mTvCartNum = (TextView) mRootView.findViewById(R.id.tv_cart_num);
        mViewPager = (ViewPager) mRootView.findViewById(R.id.view_pager);
        mTabLayout = (TabLayout) mRootView.findViewById(R.id.tab_layout);
        mLlGoodsPromotion = (LinearLayout) mRootView.findViewById(R.id.ll_goods_promotion);
        mFavorableLayout = (FavorableLayout) mRootView.findViewById(R.id.favorable_layout);
        tvPriceOntrast = (TextView) mRootView.findViewById(R.id.tv_price_ontrast); //昨日比价
        tvLogisticsInfo = (TextView) mRootView.findViewById(R.id.tv_logistics_info); //物流
        tvLogisticsPrice = (TextView) mRootView.findViewById(R.id.tv_logistics_price); //运费
        mViewPlaceHolder = mRootView.findViewById(R.id.view_placeHolder);
        mLlActiveHeader = (LinearLayout) mRootView.findViewById(R.id.ll_active_header);
        mTvPriceActive = (TextView) mRootView.findViewById(R.id.tv_price);
        mTvActiveStyle = (TextView) mRootView.findViewById(R.id.tv_active);
        mTvPricePast = (TextView) mRootView.findViewById(R.id.tv_price_past);
        mTvTipActive = (TextView) mRootView.findViewById(R.id.tv_tip_active);
        mTimerLayout = (TimerLayout) mRootView.findViewById(R.id.timer_layout);
        mTvLessNumber = (TextView) mRootView.findViewById(R.id.tv_less_number);
        mTvBgCircle = (TextView) mRootView.findViewById(R.id.iv_bg_circle);
        mLlServicePhone = (LinearLayout) mRootView.findViewById(R.id.ll_service_phone);
        mTvPhone = (TextView) mRootView.findViewById(R.id.tv_phone);
        mTvSaleOff = (TextView) mRootView.findViewById(R.id.tv_sale_off);
        mTvMinNum = (TextView) mRootView.findViewById(R.id.tv_min_num);

        Bundle bundle = getArguments();
        goodsId = bundle.getString(Intents.HOME_GOODS_ID);

        if (TextUtils.isEmpty(goodsId)) {
            UIUtils.showToast(UIUtils.getString(R.string.parse_error));
            mActivity.finish();
        }

        initViewPager();
        initEvent();

        mGoodsDetailBuyManager.initBuyDialog(mActivity);

        mPresenter.start();
    }

    private void initViewPager() {
        if (null == mPagerAdapter) {
            mPagerAdapter = new GoodsDetailPagerAdapter(getChildFragmentManager());
            // 添加三个页面
            mGoodsDetailInfoFragment = GoodsDetailInfoFragment.getInstance();
            mGoodsDetailStandardFragment = GoodsDetailStandardFragment.getInstance();
            mGoodsDetailValueFragment = GoodsDetailValueFragment.getInstance();
            addFragment();
        }

        new GoodsDetailInfoPresenter(mGoodsDetailInfoFragment);
        new GoodsDetailStandardPresenter(mGoodsDetailStandardFragment);
        new GoodsDetailValuePresenter(mGoodsDetailValueFragment);
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setOffscreenPageLimit(2);
        mTabLayout.setupWithViewPager(mViewPager);
    }

    private void addFragment() {
        mPagerAdapter.addFragment(mGoodsDetailInfoFragment);
        mPagerAdapter.addFragment(mGoodsDetailStandardFragment);
        mPagerAdapter.addFragment(mGoodsDetailValueFragment);
    }

    @Override
    public void setViewPager(GoodsDetailResponse.DataBean dataBean) {
        for (int i = 0; i < mPagerAdapter.getCount(); i++) {
            Fragment fragment = mPagerAdapter.getItem(i);
            switch (i) {
                case 0:
                    GoodsDetailInfoFragment fg0 = (GoodsDetailInfoFragment) fragment;
                    fg0.setGoodsInfo(dataBean.getGoodsDescUrl());
                    break;
                case 1:
                    GoodsDetailStandardFragment fg1 = (GoodsDetailStandardFragment) fragment;
                    fg1.setGoodsInfo(dataBean);
                    break;
                case 2:
                    Goods goods = dataBean.getGoodsInfo();
                    String goodsId = goods.getGoodsId();
                    GoodsDetailValueFragment fg2 = (GoodsDetailValueFragment) fragment;
                    fg2.setGoodsInfo(goodsId);
                    break;
            }
        }
    }

    @Override
    public void setCanBuyStatus(boolean canBuy) {
        mCanBuy = canBuy;
        if (canBuy) {
            mTvCart.setOnClickListener(this);
            mTvToBuy.setOnClickListener(this);
            mTvCart.setBackgroundColor(UIUtils.getColor(R.color.btn_half_red));
            mTvToBuy.setBackgroundColor(UIUtils.getColor(R.color.btn_red));
        } else {
            mTvCart.setOnClickListener(null);
            mTvToBuy.setOnClickListener(null);
            mTvCart.setBackgroundColor(UIUtils.getColor(R.color.btn_gray));
            mTvToBuy.setBackgroundColor(UIUtils.getColor(R.color.btn_gray));
        }
    }

    @Override
    public void setViewGone() {
        mRlGoodsBottom.setVisibility(View.GONE);
        mLlGoodsPrice.setVisibility(View.GONE);
        mViewPager.setVisibility(View.GONE);
        mTabLayout.setVisibility(View.GONE);
        mIbtnShare.setVisibility(View.GONE);
    }

    @Override
    public void setViewVisible() {
        mRlGoodsBottom.setVisibility(View.VISIBLE);
        mLlGoodsPrice.setVisibility(View.VISIBLE);
        mViewPager.setVisibility(View.VISIBLE);
        mTabLayout.setVisibility(View.VISIBLE);
        mIbtnShare.setVisibility(View.VISIBLE);
    }

    @Override
    public void showDialog() {
        mLoadingDialog.show();
    }

    @Override
    public void dismissDialog() {
        if (!mActivity.isFinishing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public String getPagerTag() {
        return TAG;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_goods_detail;
    }

    @Override
    public void showToast(String text) {
        UIUtils.showToast(text);
    }

    @Override
    public String getGoodsId() {
        return goodsId;
    }

    private void initEvent() {
        mRlCollect.setOnClickListener(this);
        mIbtnShare.setOnClickListener(this);
        mIbtnBack.setOnClickListener(this);
        mTvPriceActive.setOnClickListener(this);
        mTvGoodsPrice.setOnClickListener(this);
        mRlytGoToShoppingCart.setOnClickListener(this);
        mLlGoodsPrice
                .getViewTreeObserver()
                .addOnGlobalLayoutListener(
                        new ViewTreeObserver.OnGlobalLayoutListener() {
                            @Override
                            public void onGlobalLayout() {
                                // scrollHeight = mLlGoodsPrice.getHeight() - mToolbar.getHeight
                                // () - mLlGoodsShop.getHeight();
                                scrollHeight = mBannerView.getHeight() - mToolbar.getHeight();
                                mLlGoodsPrice
                                        .getViewTreeObserver()
                                        .removeGlobalOnLayoutListener(this);
                            }
                        });

        mAppbarLayout.addOnOffsetChangedListener(
                new AppBarLayout.OnOffsetChangedListener() {
                    @Override
                    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                        try {
                            int currentAlpha; //当前alpha值
                            if (verticalOffset != 0) {
                                currentAlpha = -verticalOffset * 255 / scrollHeight;
                                //避免更改太频繁
                                if (Math.abs(currentAlpha - alpha) < 3) {
                                    return;
                                }
                                alpha = currentAlpha;
                            } else {
                                alpha = 0;
                                currentAlpha = 0;
                            }
                            if (currentAlpha > 255) {
                                currentAlpha = 255;
                            }
                            mToolbar.setBackgroundColor(Color.argb(currentAlpha, 255, 255, 255));
                            mTvTitle.setTextColor(Color.argb(currentAlpha, 63, 38, 49));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

        mTimerLayout.setOnTimeChangeListener(
                new TimerLayout.OnTimeChangeListener() {
                    @Override
                    public void onLeaveTimeChanged(int viewId, long leaveTime) {
                        //正在进行
                        if (leaveTime == 0 && mIsRunning) {
                            //重新刷新数据
                            mPresenter.start();
                        }
                    }
                });
        mIbtnBack.setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mActivity.finish();
                    }
                });
        mRlHome.setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //进入首页
                        UmengUtils.onEvent(mActivity, R.string.umeng_goods_detail_back_home);
                        MainActivity.actionStart(mActivity, HomeFragment.TAG);
                    }
                });
        mRlCart.setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //进入购物车
                        UmengUtils.onEvent(mActivity, R.string.umeng_goods_detail_cart);
                        MainActivity.actionStart(mActivity, ShoppingCartFragment.TAG);
                    }
                });

        mTvShopEnter.setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String supplierId = mShop.getSupplierId();
                        ShopDetailActivity.actionStart(mActivity, supplierId);
                    }
                });
        mTvPhone.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                CallPhoneDialog dialog = new CallPhoneDialog(mActivity);
                dialog.show();
                dialog.setPhoneNum(mPhone);
            }
        });
    }

    @Override
    public void toConfirmOrderActivity(String json) {
        ConfirmOrderActivity.actionStart(mActivity, false);
    }

    @Override
    public void setCartStyle(int num) {
        mTvCartNum.setVisibility(num == 0 ? View.GONE : View.VISIBLE);
        String cartNum = num + "";
        if (num > 99) {
            cartNum = "99+";
        }
        mTvCartNum.setText(cartNum);
    }

    @Override
    public void setCollectStyle(boolean hasCollect) {
        mHasCollect = hasCollect;
        mIvCollect.setImageResource(hasCollect ? R.mipmap.ic_collect : R.mipmap.ic_collect_empty);
    }

    @Override
    public void setGoodsInfo(GoodsDetailResponse.DataBean dataBean) {
        mDataBean = dataBean;

        Goods mGoods = dataBean.getGoodsInfo();
        mShop = dataBean.getShopInfo();

        //抢购商品限购数量
        int limitNumber = mGoods.getLimitNumber();
        //-1是不限购 0是购买完 大于1是能购买的数量
        if (mCanBuy) //当能买的时候
        {
            setCanBuyStatus(limitNumber != 0);
        }

        //banner图片信息
        if (null != dataBean.getGoodsImg() && dataBean.getGoodsImg().size() != 0) {
            mBannerView.setData(dataBean.getGoodsImg());
        }

        //title名
        String goodsName = mGoods.getGoodsName();
        mTvTitle.setText(goodsName);


        String supplierId = mGoods.getSupplierId();
        /*  //销售方式
        String style = supplierId.equals("0") ? UIUtils.getString(R.string
        .goods_platform_self_sell) : UIUtils.getString(R.string.goods_platform_other_sell);
        SpannableString span = new SpannableString(UIUtils.getString(R.string.goodsdetail_name,
        style, goodsName));
        //改变文字颜色
        span.setSpan(new ForegroundColorSpan(0xfff81b5f), 0, style.length() + 2, Spanned
        .SPAN_INCLUSIVE_INCLUSIVE);
        mTvGoodsName.setText(span);*/
        //商品名
        mTvGoodsName.setText(goodsName);
        //设置活动数据
        setGoodsTypeData(mGoods);
        //是否显示市场价和单瓶价
        if (!mGoods.getAvgShopPriceFloat().equals("0.00")) {
            mLlSigleUnit.setVisibility(View.VISIBLE);
            //市场价
            mTvMarketPrice.setText(
                    TextRenderUtils.getBeautyPrice(
                            mGoods.getAvgMarketPriceFloat(),
                            UIUtils.getString(R.string.goodsdetail_Single_unit),
                            UIUtils.dp2px(13),
                            UIUtils.dp2px(11)));
            //单瓶
            mTvProfit.setText(
                    TextRenderUtils.getBeautyPrice(
                            mGoods.getAvgShopPriceFloat(),
                            null,
                            UIUtils.dp2px(13),
                            UIUtils.dp2px(11)));
        } else {
            mLlSigleUnit.setVisibility(View.GONE);
        }

        //已售
        mTvSold.setText(UIUtils.getString(
                R.string.goodsdetail_unit, mGoods.getSalesNum(), mGoods.getGoodsUnit()));
        //起定量
        int minNum = mGoods.getMinNumber() > 0 ? mGoods.getMinNumber() : 1;
        mTvMinNum.setText(minNum + mGoods.getGoodsUnit());

        //物流
        tvLogisticsInfo.setText(mGoods.getDeliverys());

        //运费
        //        if (PriceUtils.isLogin()) {
        mLlLogistics.setVisibility(View.VISIBLE);
        if (mGoods.getLogisticsFee().equals("0") || mGoods.getLogisticsFee().equals("0.00")) {
            tvLogisticsPrice.setText(
                    UIUtils.getString(R.string.goodsdetail_logistics_free));
        } else {
            SpannableStringBuilder builder = new SpannableStringBuilder();
            String fee1 = UIUtils.getString(R.string.goodsdetail_logistics_fee1, mGoods.getLogisticsFee());
            String fee2 = UIUtils.getString(R.string.goodsdetail_logistics_fee2, mGoods.getFreeMoney());

            SpannableString spannableString1 = TextRenderUtils.getAbsoluteSizeText(fee1, UIUtils.dp2px(13));
            SpannableString spannableString2 = TextRenderUtils.getAbsoluteSizeText(fee2, UIUtils.dp2px(11));

            builder.append(spannableString1).append(spannableString2);

            tvLogisticsPrice.setText(builder);
        }
        //        } else {
        //            mLlLogistics.setVisibility(View.GONE);
        //        }

        //客服
        mPhone = mGoods.getServicePhone();
        if (TextUtils.isEmpty(mPhone)) {
            mLlServicePhone.setVisibility(View.GONE);
        } else {
            mLlServicePhone.setVisibility(View.VISIBLE);
            mTvPhone.setText(mPhone);
        }
        //判断加入购物车，是活动商品  0 不能  1能
        mCanCart = dataBean.getCanCart() != 0;
        mTvCart.setVisibility(mCanCart ? View.VISIBLE : View.GONE);
        mViewPlaceHolder.setVisibility(mCanCart ? View.GONE : View.INVISIBLE);
        //是否能购买
        boolean canBuyNow = dataBean.getCanBuyNow() != 0;
        mTvToBuy.setVisibility(canBuyNow ? View.VISIBLE : View.INVISIBLE);


        //活动说明
        mGoodsDetailBuyManager.setActiveDesc(dataBean, mLlGoodsPromotion, mFavorableLayout);

        //服务商
        String server_brand = supplierId.equals("0")
                ? UIUtils.getString(R.string.name_brand)
                : mShop.getSupplierName();
        mTvTip.setText(UIUtils.getString(R.string.goodsdetail_tip, server_brand));

        if (!mGoods.getSupplierId().equals("0")) {
            mLlGoodsShop.setVisibility(View.VISIBLE);
            //店铺信息
            ImageLoader.loadShopLogo(mActivity, mIvShopInfoImage, mShop.getShopLogo());
            mTvShopName.setText(mShop.getSupplierName());

            // 商品种类
            int goodsNumber = mShop.getGoodsNum();
            // 商品销量
            int saleNumber = mShop.getSalenum();
            mTvShopDetail.setText(
                    UIUtils.getString(R.string.shop_sales_count, goodsNumber));

        } else {
            mLlGoodsShop.setVisibility(View.GONE);
        }
        // 商品库存
        goodsStockNumber = mGoods.getStockNumber() > 0 ? mGoods.getStockNumber() : 0;
        mTvStockNumber.setText(
                UIUtils.getString(
                        R.string.goodsdetail_unit,
                        mGoods.getGoodsNumberDesc(),
                        mGoods.getGoodsUnit()));
        mTvBgCircle.setVisibility(goodsStockNumber == 0 ? View.VISIBLE : View.GONE);
        mTvBgCircle.setText(UIUtils.getString(R.string.sale_off));
        if (goodsStockNumber == 0) {
            mTvSaleOff.setVisibility(View.VISIBLE);
            mViewPlaceHolder.setVisibility(View.VISIBLE);
            mTvToBuy.setVisibility(View.GONE);
            mTvCart.setVisibility(View.GONE);
        }

        //登陆后，存储数据到数据库
        mGoodsDetailBuyManager.insertDataToRealm(mGoods);
    }

    /**
     * 根据商品活动类型设置数据
     */
    private void setGoodsTypeData(Goods goods) {
        //商品活动类型
        int goodsType = goods.getGoodsType();
        switch (goodsType) {
            case Goods.TYPE.LIMIT: {
                //限时购
                mTvActiveStyle.setText(
                        UIUtils.getString(R.string.goodsdetail_limit_time_price));
                showTimeLayout(goods);
                break;
            }
            case Goods.TYPE.FREE: {
                //免费赠
                mTvPricePast.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                mLlPrice.setVisibility(View.GONE);
                mLlActiveHeader.setVisibility(View.VISIBLE);
                mTimerLayout.setVisibility(View.GONE);
                mTvLessNumber.setVisibility(View.VISIBLE);
                mTvActiveStyle.setVisibility(View.GONE);
                mTvPriceActive.setText(
                        TextRenderUtils.getBeautyPrice(
                                goods.getLimitPrice(),
                                goods.getGoodsUnit(),
                                UIUtils.dp2px(20),
                                UIUtils.dp2px(16)));
                mTvPricePast.setText(
                        TextRenderUtils.getBeautyPrice(
                                goods.getShopPriceFloat(),
                                null,
                                UIUtils.dp2px(14),
                                UIUtils.dp2px(12)));
                mTvTipActive.setText(UIUtils.getString(R.string.goodsdetail_less_number));
                mTvLessNumber.setText(
                        UIUtils.getString(
                                R.string.goodsdetail_unit,
                                goodsStockNumber + "",
                                goods.getGoodsUnit()));
                mTvToBuy.setText(UIUtils.getString(R.string.goodsdetail_free_get));
                break;
            }
            case Goods.TYPE.SECOND_KILL: {
                //秒杀
                mTvActiveStyle.setText(UIUtils.getString(R.string.goodsdetail_second_price));
                showTimeLayout(goods);
                break;
            }
            default:
                //其他
                mLlPrice.setVisibility(View.VISIBLE);
                mLlActiveHeader.setVisibility(View.GONE);
                //批发价
                mTvGoodsPrice.setText(
                        TextRenderUtils.getBeautyPrice(
                                goods.getShopPriceFloat(),
                                goods.getGoodsUnit(),
                                UIUtils.dp2px(18),
                                UIUtils.dp2px(14)));
                //比价
                PriceUtils.setGoodsDetailChargeChange(tvPriceOntrast, goods.getContrast());
                break;
        }
    }

    private void showTimeLayout(Goods goods) {
        mTvPricePast.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        mLlPrice.setVisibility(View.GONE);
        mLlActiveHeader.setVisibility(View.VISIBLE);
        mTimerLayout.setVisibility(View.VISIBLE);
        mTvLessNumber.setVisibility(View.GONE);
        mTvPriceActive.setText(
                TextRenderUtils.getBeautyPrice(
                        goods.getLimitPrice(),
                        goods.getGoodsUnit(),
                        UIUtils.dp2px(20),
                        UIUtils.dp2px(16)));
        mTvPricePast.setText(
                TextRenderUtils.getBeautyPrice(
                        goods.getShopPriceFloat(), null, UIUtils.dp2px(14), UIUtils.dp2px(12)));
        mTimerLayout.setDividerColor(0xffffffff);

        long nowTime = goods.getNowTime(); //服务器当前时间
        //活动开始时间
        long startTime = goods.getStartTime();
        long endTime = goods.getEndTime(); //活动结束时间

        calculateTime(nowTime, startTime, endTime);
    }

    private void calculateTime(long nowTime, long startTime, long endTime) {
        if (nowTime >= endTime) {
            //已结束
            mTimerLayout.setLeaveTime(0);
            mTvTipActive.setText(UIUtils.getString(R.string.finished));
            mTvBgCircle.setVisibility(View.VISIBLE);
            mTvBgCircle.setText(UIUtils.getString(R.string.finished));
        } else if (nowTime <= startTime) {
            //未开始
            mIsRunning = true;
            mTvTipActive.setText(UIUtils.getString(R.string.goodsdetail_less_time_start));
            mTimerLayout.setLeaveTime(startTime - nowTime);
        } else {
            mIsRunning = true;
            mTvTipActive.setText(UIUtils.getString(R.string.goodsdetail_less_time_end));
            mTimerLayout.setLeaveTime(endTime - nowTime);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        mBannerView.startPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        mBannerView.stopPlay();
    }

    @Override
    public void onClick(View v) {
        //        boolean login = PriceUtils.isLogin();
        //        if (login) {
        switch (v.getId()) {
            case R.id.tv_to_cart:
                UmengUtils.onEvent(mActivity, R.string.umeng_goods_detail_add_cart);
                // 库存处理
                if (goodsStockNumber == 0 || mDataBean.getGoodsInfo().getMinNumber() > goodsStockNumber) {
                    showToast(UIUtils.getString(R.string.stock_none_hint));
                    return;
                }
                mGoodsDetailBuyManager.setDialogData(
                        mDataBean, GoodsDetailResponse.BuyType.CART, mPresenter);
                break;
            case R.id.tv_to_buy:
                UmengUtils.onEvent(mActivity, R.string.umeng_goods_detail_buy);
                // 库存处理
                if (goodsStockNumber == 0 || mDataBean.getGoodsInfo().getMinNumber() > goodsStockNumber) {
                    showToast(UIUtils.getString(R.string.stock_none_hint));
                    return;
                }
                mGoodsDetailBuyManager.setDialogData(
                        mDataBean, GoodsDetailResponse.BuyType.BUY, mPresenter);
                break;
            case R.id.rl_collect:
                UmengUtils.onEvent(mActivity, R.string.umeng_goods_detail_collect);
                mPresenter.collectGoods(goodsId, mHasCollect);
                break;
            case R.id.ibtn_share:
                UmengUtils.onEvent(mActivity, R.string.umeng_goods_detail_share);
                ShareEntity shareEntity = mPresenter.getShareEntity();
                ShareDialog shareDialog = new ShareDialog(mActivity);
                shareDialog.show();
                shareDialog.setShareLinkData(shareEntity);
                break;
            case R.id.rlty_go_to_shopping_cart:
                //进入购物车
                mActivity.finish();
                UmengUtils.onEvent(mActivity, R.string.umeng_goods_detail_cart);
                MainActivity.actionStart(mActivity, ShoppingCartFragment.TAG);
                break;
        }
        //        } else {
        //            LoginActivity.actionStart(mActivity);
        //        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mGoodsDetailBuyManager.closeHistoryRealm();
        mTimerLayout.stopTimer();

        // 如果当前商品是秒杀，并且当前商品的库存为0
        mPresenter.postRefreshHomeSecondKillEvent();
    }

    @Override
    public void notifyDataChanged() {
        mPresenter.start();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshGoodsDetail(RefreshGoodsDetailEvent event) {
        mPresenter.start();
    }

    @Override
    public boolean canCart() {
        return mCanCart;
    }
}
